//
//  WmcAlbumPhotoListVC.swift
//  YPWatermarkCamera
//
//  Created by yupao_ios_macmini06 on 2022/10/28.
//

import MJRefresh
import UIKit

/// 复用部分

class WmcAlbumPhotoListVC: WmcBaseVC, WmcStatefulViewController {
    let vm: WmcAlbumPhotoListVM

    init(vm: WmcAlbumPhotoListVM) {
        self.vm = vm
        super.init(nibName: nil, bundle: nil)
    }

    @available(*, unavailable)
    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // Lifecycle

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setupInitialViewState()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        if vm.type == .memberPhoto {
            title = "成员照片"
        } else {
            title = vm.title
        }

        fetchData()
        /// 删除照片需要刷新页面数据
        WmcNotificationManager.shared.addObserver(type: .deletePhotoSucceed) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.fetchData()
        }

        setupPlaceholders()
    }

    /// 设置占位视图
    /// - Returns: description
    func setupPlaceholders() {
        loadingView = WmcLoadingView()
        emptyView = currentEmptyView
        let errView = WmcErrorView()
        errView.refreshClosure = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.fetchData()
        }
        errorView = errView
    }

    // Internal

    override func makeUI() {
        view.backgroundColor = UIColor.wmc_gray_F7F8FA
        addSubview(collectionView)

        collectionView.snp.makeConstraints { make in
            make.top.equalTo(8)
            make.left.right.bottom.equalToSuperview()
        }
    }

    override func bindViewAction() {
        NotificationCenter.default.addObserver(self, selector: #selector(photoAlbumDataDidChange(notification:)), name: NSNotification.Name(rawValue: "com.watermark.classifyAlbumDataDidChange"), object: nil)
    }

    @objc
    func photoAlbumDataDidChange(notification _: Notification) {
        fetchData(showLoading: true)
    }

    private lazy var collectionView: UICollectionView = {
        let collectView = UICollectionView(frame: self.view.bounds, collectionViewLayout: self.layout)
        collectView.backgroundColor = .wmc_white_FFFFFF
        collectView.delegate = self
        collectView.dataSource = self
        collectView.showsVerticalScrollIndicator = true
        collectView.register(WmcCloudPhotoCell.self, forCellWithReuseIdentifier: "WmcCloudPhotoCell")
        collectView.register(WmcCloudAllPhotoCollectionHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "WmcCloudAllPhotoCollectionHeaderView")
        collectView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.fetchData(showLoading: false)
        })

        collectView.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.loadMore()
        })
        return collectView
    }()

    lazy var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        let width = (self.view.bounds.width - 38) / 3.0
        layout.itemSize = CGSize(width: width, height: width)
        layout.minimumLineSpacing = 3
        layout.minimumInteritemSpacing = 3
        layout.sectionInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
        layout.sectionHeadersPinToVisibleBounds = false
        return layout
    }()

    private lazy var currentEmptyView: WmcCloudAllPhotoEmptyView = {
        let view = WmcCloudAllPhotoEmptyView()
        return view
    }()

    private func fetchData(showLoading: Bool = true) {
        if showLoading {
            WmcHudManager.loading()
        }

        startLoading()
        vm.refresh { [weak self] _ in
            guard let weakSelf = self else { return }
            if showLoading {
                WmcHudManager.dismiss()
            }
            weakSelf.collectionView.reloadData()
            weakSelf.collectionView.mj_header?.endRefreshing()
            if weakSelf.vm.hasNoMore {
                weakSelf.collectionView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                weakSelf.collectionView.mj_footer?.resetNoMoreData()
            }
            weakSelf.endLoading()
        } failure: { [weak self] error in
            guard let weakSelf = self else { return }
            if showLoading {
                WmcHudManager.dismiss()
            }
            weakSelf.collectionView.mj_header?.endRefreshing()
            WmcHudManager.toast("网络不佳，请稍后再试")
            weakSelf.endLoading(animated: true, error: error, completion: nil)
        }
    }

    private func loadMore() {
        vm.loadMore { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.collectionView.reloadData()
            if weakSelf.vm.hasNoMore {
                weakSelf.collectionView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                weakSelf.collectionView.mj_footer?.endRefreshing()
            }
        } failure: { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.collectionView.mj_footer?.endRefreshing()
            WmcHudManager.toast("网络不佳，请稍后再试")
        }
    }
}

// MARK: - UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout

extension WmcAlbumPhotoListVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func numberOfSections(in _: UICollectionView) -> Int {
        return vm.dataSource.count
    }

    func collectionView(_: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let group = vm.dataSource.yp.object(at: section) {
            return group.list.count
        }
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WmcCloudPhotoCell", for: indexPath) as! WmcCloudPhotoCell
        if let group = vm.dataSource.yp.object(at: indexPath.section),
           let model = group.list.yp.object(at: indexPath.row)
        {
            /// cell.configure(model: model)
            cell.bindModel(model)
        }
        return cell
    }

    // 设置 区头和区尾
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let headerView: WmcCloudAllPhotoCollectionHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "WmcCloudAllPhotoCollectionHeaderView", for: indexPath) as! WmcCloudAllPhotoCollectionHeaderView
        if let group = vm.dataSource.yp.object(at: indexPath.section) {
            headerView.bindModel(group)
        }
        return headerView
    }

    func collectionView(_: UICollectionView, layout _: UICollectionViewLayout, referenceSizeForHeaderInSection _: Int) -> CGSize {
        return CGSize(width: view.bounds.width, height: 41)
    }

    func collectionView(_: UICollectionView, layout _: UICollectionViewLayout, referenceSizeForFooterInSection _: Int) -> CGSize {
        return CGSize(width: view.bounds.width, height: 0)
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let _ = collectionView.cellForItem(at: indexPath) as? WmcCloudPhotoCell else { return }
        tabBarController?.tabBar.isHidden = true
        var index: Int?
        var indexTemp = 0
        for (sectionIndex, section) in vm.dataSource.enumerated() {
            for (rowIndex, _) in section.list.enumerated() {
                if sectionIndex == indexPath.section, rowIndex == indexPath.row {
                    index = indexTemp
                    break
                }
                indexTemp += 1
            }
            if index != nil {
                break
            }
        }

        guard let index = index else {
            return
        }
        guard let album = vm.teamAblum else { return }

        let browser = WmcTeamAlbumBrowser(album: album,
                                          browserDataSource: vm.browserDataSource,
                                          originalDataSource: vm.originalDataSource)
        let model = vm.originalDataSource[index]
        browser.browserPhotos(model: model, title: vm.browserTitle)
    }
}

extension WmcAlbumPhotoListVC {
    func hasContent() -> Bool {
        return vm.dataSource.count > 0
    }

    func handleErrorWhenContentAvailable(_: Error) {
        // 处理错误
    }
}
